var tableIns1;
var tree = layui.tree;
var table = layui.table;
var form = layui.form;
var layer = layui.layer;
var $ = jQuery = layui.jquery;
var laydate = layui.laydate;
var util = layui.util;


layui.use(['table', 'layer', 'laydate'], function () {

    //加载table
    tableIns1 = table.render({
        elem: '#showTable'
        , contentType: 'application/json'
        // , headers: {"authorization": token}
        , url: ctx + 'sysRole/listByPage' //数据接口
        , method: 'POST'
        , limit: 15
        , limits: [15, 25, 50, 100]
        , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
            // console.log(res);
        }
        , cols: [
            [
                {type: 'checkbox', fixed: 'left'},
                {field: 'roleId', title: '角色编号'},
                {field: 'roleName', title: '角色名称'},
                {field: 'roleKey', title: '权限字符'},
                {field: 'roleSort', title: '显示顺序', sort: true},
                {field: 'status', align: 'center', title: '角色状态', templet: '#switchTpl'},
                {field: 'createTime', align: 'center', title: '创建时间'},
                {width: 300, align: 'center', toolbar: "#tool", title: '操作'}
            ]
        ]
        , page: {
            layout: ['prev', 'page', 'next', 'refresh', 'skip', 'count', 'limit']
            , first: '首页' //不显示首页
            , last: '尾页' //不显示尾页
            , groups: 3 //显示 3个连续页码
        }
        , toolbar: '#toolbar'
    });
    //表头工具
    table.on('toolbar(showTable)', function (obj) {
        switch (obj.event) {
            case 'batchDeleted':
                var checkStatus = table.checkStatus(obj.config.id);
                var data = checkStatus.data;
                if (data.length == 0) {
                    layer.msg("请选择要批量删除的列");
                } else {
                    var ids = [];
                    $(data).each(function (index, item) {
                        ids.push(item.roleId);       //更换成表的id
                    });
                    tipDialog(ids);
                }
                break;
            case 'add':
                layer.open({
                    type: 1,
                    title: "添加",
                    area: ["800px", "640px"],
                    Number: 9000000,   //自动关闭的时间
                    maxmin: true, // 最大最小化。
                    resize: true, // 是否允许拉伸
                    anim: 2,
                    content: $('#add'), //添加表单到弹出层
                })
                break;
        }
        ;
    });

    let demoId2 = [];
    //列操作
    table.on('tool(showTable)', function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case 'del':
                var ids = [];
                ids.push(data.roleId);   //更换成表的id
                tipDialog(ids);
                break;
            case 'edit':
                document.getElementById("roleId").value = data.roleId;
                document.getElementById("roleName").value = data.roleName;
                document.getElementById("roleKey").value = data.roleKey;
                document.getElementById("roleSort").value = data.roleSort;
                document.getElementById("remark").value = data.remark;
                $.ajax({
                    url: ctx + 'sysRole/data1?id=' + data.roleId,
                    type: 'GET',
                    contentType: 'application/json; charset=UTF-8',
                    dataType: "json",
                    success: function (res) {
                        demoId2 = res.li;  //全选集合
                        //基本演示
                        tree.render({
                            elem: '#test11'
                            , data: res.list
                            , showCheckbox: true  //是否显示复选框
                            , id: 'demoId2'
                            , isJump: true //是否允许点击节点时弹出新窗口跳转
                            , click: function (obj) {
                                // layer.msg('状态：'+ obj.state + '<br>节点数据：' + JSON.stringify(data));
                            }
                        });
                    }
                })
                layer.open({
                    type: 1,
                    title: "修改",
                    area: ["800px", "700px"],
                    Number: 9000000,   //自动关闭的时间
                    maxmin: true, // 最大最小化。
                    resize: true, // 是否允许拉伸
                    anim: 2,
                    content: $('#up'), //添加表单到弹出层
                })
                break;
            case 'dist':
                sessionStorage.setItem('id', data.roleId);
                // layer.full(   //开启即最大
                layer.open({
                    type: 2
                    , title: "分配用户"
                    , shadeClose: false
                    , shade: false
                    , anim: 2
                    , area: ['90%', '90%']
                    , maxmin: true// 最大最小化。
                    , isOutAnim: true
                    // ,btn: ['关闭']
                    , content: ctx + 'sysUserRole/assign?id=' + data.roleId //添加表单到弹出层
                    , end: function (index, layero) {
                        //按钮【按钮一】的回调
                        console.log("11111111111");
                    }
                })
            // )


        }
    });

    //导出
    $('#export').on('click', function () {
        //原先分页limit
        var exportParams = {
            limit: 10000,
            key: $("#key").val()
        };
        let url = ctx + "sysRole/listByPage"
        coreUtilsendPost(url, exportParams, function (res) {
            //初始化渲染数据
            if (res.data != null && res.data.records != null) {
                table.exportFile(tableIns1.config.id, res.data.records, 'xls');
            }
        });
    });

    //删除
    var tipDialog = function (ids) {
        layer.open({
            content: "确定要删除么?",
            yes: function (index, layero) {
                layer.close(index); //如果设定了yes回调，需进行手工关闭
                let url = ctx + "sysRole/delete"
                coreUtilsendDelete(url, ids, function (res) {
                    layer.msg(res.msg, {time: 1000}, function () {
                        search();
                    });
                });
            }
        });
    };

    //返回
    $("#btn_cancel").click(function () {
        layer.closeAll(); //关闭所有弹窗
        return false;
    });
    //返回
    $("#btn_cancel1").click(function () {
        layer.closeAll(); //关闭所有弹窗
        return false;
    });


    var role_menu = [];
    //监听保存
    let list = [];
    form.on('submit(submit)', function (data) {

        let list = data.field;
        if (list.roleId === undefined || list.roleId === null || list.roleId === "") {     //更换成表的id

            let checkedData = tree.getChecked('demoId1'); //获取选中节点的数据
            let list1 = [];
            list1.push(getChecked_list(checkedData));
            if (list.status === 'on') {
                list.status = 0;
            }
            let data1 = {
                status: list.status,
                roleSort: list.roleSort,
                roleName: list.roleName,
                roleKey: list.roleKey,
                roleId: list.roleId,
                remark: list.remark,
                list: list1
            };

            let url = ctx + "sysRole/add";
            coreUtilsendPost(url, data1, function (res) {
                $(".table_div").show();
                $(".operation").hide();
                search();
            });
        } else {

            let checkedData = tree.getChecked('demoId2'); //获取选中节点的数据
            let list1 = [];
            list1.push(getChecked_list(checkedData));
            if (list.status === 'on') {
                list.status = 0;
            }
            let data1 = {
                status: list.status,
                roleSort: list.roleSort,
                roleName: list.roleName,
                roleKey: list.roleKey,
                roleId: list.roleId,
                remark: list.remark,
                list: list1
            };

            console.log(data.field);
            let url = ctx + "sysRole/update";
            coreUtilsendPut(url, data1, function (res) {
                $(".table_div").show();
                $(".operation").hide();
                search();
            });
        }

        return false;
    });

    let demoId1 = [];
    $.ajax({
        url: ctx + 'sysRole/data',
        type: 'GET',
        contentType: 'application/json; charset=UTF-8',
        dataType: "json",
        success: function (res) {
            demoId1 = res.li;
            //基本演示
            tree.render({
                elem: '#test12'
                , data: res.list
                , showCheckbox: true  //是否显示复选框
                , name: "p"
                , id: 'demoId1'
                , isJump: true //是否允许点击节点时弹出新窗口跳转
                , click: function (obj) {
                    // layer.msg('状态：'+ obj.state + '<br>节点数据：' + JSON.stringify(data));
                }
            });
        }
    })


    function getChecked_list(data) {
        var id = "";
        $.each(data, function (index, item) {
            if (id != "") {
                id = id + "," + item.id;
            } else {
                id = item.id;
            }
            var i = getChecked_list(item.children);
            if (i != "") {
                id = id + "," + i;
            }
        });
        return id;
    }


    //按钮事件
    util.event('lay-demo', {
        setChecked: function () {
            tree.setChecked('demoId1', demoId1); //勾选指定节点
        }
        , reload: function () {
            //重载实例
            tree.reload('demoId1', {});
        }
    });

    util.event('lay-demo', {
        setChecked1: function () {
            tree.setChecked('demoId2', demoId2); //勾选指定节点
        }
        , reload1: function () {
            //重载实例
            tree.reload('demoId2', {});

        }
    });

});

//监听指定开关
form.on('switch(switchTest)', function (data) {

    console.log(data);
    layer.tips((this.checked ? '启用' : '禁用'), data.othis)
});

//监听指定开关
form.on('switch(switchTest1)', function (data) {

    console.log(data);
    layer.tips((this.checked ? '启用' : '禁用'), data.othis)
});


//执行查询
function search() {
    //这里以搜索为例
    tableIns1.reload({
        where: { //设定异步数据接口的额外参数，任意设
            key: $("#key").val()
        }
        , page: {
            curr: 1 //重新从第 1 页开始
        }
    });
};

